<template>
  <a-page-header
      style="border: 1px solid rgb(235, 237, 240)"
      :title="article.title||'标题'"
      :sub-title="article.description"
      @back="() => $router.push('/')"
  >
    <template #extra>
      <a-button type="primary" size="large" @click="submit" :disabled="!submitDisable">提交</a-button>
    </template>
  </a-page-header>

  <div style="width: 100%">
    <a-row type="flex" justify="space-around">
      <a-col :span="15">
        <a-input v-model:value="article.title" placeholder="请输入标题"/>
      </a-col>
      <a-col :span="9">
        <a-select
            :value="value"
            show-search
            :placeholder="article.cityName?article.cityName:'请择选城市或缩写'"
            :options="city"
            :filter-option="filterOption"
            @focus="handleFocus"
            @blur="handleBlur"
            @select="handleCitySelect"
            @change="handleChange"
        >
        </a-select>
      </a-col>
    </a-row>
  </div>
  <a-input v-model:value="article.description" placeholder="请输入简介"/>
  <a-affix :offset-top="top">
    <div style="border: 1px solid #ccc">
      <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
      />
      <Editor
          style="height: 300px; overflow-y: hidden;"
          v-model="valueHtml"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
      />
    </div>
    <!--    <div style="margin:auto;width: 200px">-->
    <!--      <a-space :size="44">-->
    <!--        <a-button type="primary" size="large" @click="submit" :disabled="!submitDisable">提交</a-button>-->
    <!--        <a-button size="large" @click="$router.push('/')">取消</a-button>-->
    <!--      </a-space>-->
    <!--    </div>-->
  </a-affix>
</template>
<script>

import '@wangeditor/editor/dist/css/style.css' // 引入 css

import {onBeforeUnmount, defineComponent, computed, ref, shallowRef, onMounted, reactive} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {message} from "ant-design-vue";
import axios from "axios";
import store from "@/store";
import router from "@/router";
import {useRoute, useRouter} from "vue-router";


export default {
  name: "Write",
  components: {Editor, Toolbar},
  props: {
    id: Number
  },
  setup(props) {
    //读取用户信息
    const user = computed(() => store.state.user)

    //判断是否已登陆用户，如否返回登陆页面
    const ifUser = () => {
      if (!user.value.id) {
        router.push('/login/')
      }
    }

    //创建文章对象
    const article = reactive({
      id: '0',
      title: '',
      description: '',
      cityId: '1',
      content: '',
      userId: user.value.id,
      cityName: ''
    });

    /**
     * 城市选择框
     * @type
     */
    const city = ref();
    //城市选择框默认值
    const value = ref(undefined)

    async function getCity() {
      let res = await axios.get('http://192.168.10.73:8880/city/list')
      const result = res.data
      if (result.status === 10000) {
        city.value = result.content
        // console.log(city.value)
      }
    }

    const handleChange = value => {
      article.cityId = value;
      console.log(`selected ${value}`);
    };
    const handleBlur = () => {
      console.log('blur');
    };
    const handleFocus = () => {
      console.log('focus');
      // message.success('fo')
    };
    const handleCitySelect = value => {
      article.cityId = value;
    }
    //过滤城市选择框
    const filterOption = (input, option) => {
      // console.log(option.spell)
      return option.spell.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    };

    /**
     * wangeditor输入框
     * @type
     */
        // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()
    // 内容 HTML
    const valueHtml = ref('<p>hello</p>')

    const toolbarConfig = {
      excludeKeys: [
        'underline',
        'codeBlock',
        'insertVideo',
        'insertLink',
        'divider',
        'fontFamily',
        'header1',
        'header2',
        'header3',
        'clearStyle',
        'redo',
        'undo',
        'code',
        'headerSelect',
        'italic',
        'group-more-style' // 排除菜单组，写菜单组 key 的值即可
      ],
      toolbarKeys: [
        'uploadImage',
        '|',
        'fontSize', 'bold', "through", 'color', 'bgColor', "emotion",
        "blockquote", "insertTable", '|',
        "todo", "bulletedList", "numberedList",
        '|',
        "fullScreen"
      ]
    }
    const editorConfig = {MENU_CONF: {}, placeholder: '请输入内容...'}
    editorConfig.MENU_CONF['uploadImage'] = {
      server: 'http://192.168.10.73:8880/article/upload', // 上传图片地址

      timeout: 5 * 1000, // 5s

      fieldName: 'img',
      meta: {userId: user.value.id},// 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
      // metaWithUrl: true, // 参数拼接到 url 上
      // headers: {Accept: 'text/x-json'},
      maxFileSize: 10 * 1024 * 1024, // 10M
      // base64LimitSize: 5 * 1024, // 5kb 以下插入 base64

      maxNumberOfFiles: 10,// 最多可上传几个文件，默认为 100

      onBeforeUpload(files) {
        console.log('onBeforeUpload', files)
        return files // 返回哪些文件可以上传
        // return false 会阻止上传
      },
      onProgress(progress) {
        console.log('onProgress', progress)
      },
      onSuccess(file, res) {
        console.log('onSuccess', file, res)
      },
      onFailed(file, res) {
        alert(res.message)
        console.log('onFailed', file, res)
      },
      onError(file, err, res) {
        alert(err.message)
        console.error('onError', file, err, res)
      },

      // // 用户自定义插入图片
      // customInsert(res, insertFn) {
      //   console.log('customInsert', res)
      //   const imgInfo = res.data[0] || {}
      //   const { url, alt, href } = imgInfo
      //   if (!url) throw new Error(`Image url is empty`)

      //   // 自己插入图片
      //   console.log('自己插入图片', url)
      //   insertFn(url, alt, href)
      // },

      // // 用户自定义上传图片
      // customUpload(file, insertFn) {
      //   console.log('customUpload', file)

      //   return new Promise((resolve) => {
      //     // 插入一张图片，模拟异步
      //     setTimeout(() => {
      //       const src = `https://www.baidu.com/img/flexible/logo/pc/result@2.png?r=${Math.random()}`
      //       insertFn(src, '百度 logo', src)
      //       resolve('ok')
      //     }, 500)
      //   })
      // },
// // 自定义选择图片（如图床）
      // customBrowseAndUpload(insertFn) {
      //   alert('自定义选择图片，如弹出图床')

      //   // 插入一张图片，模拟异步
      //   setTimeout(() => {
      //     const src = 'https://www.baidu.com/img/flexible/logo/pc/result@2.png'
      //     insertFn(src, '百度 logo', src) // 插入图片
      //   }, 500)
    }

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
      // console.log(editor.getAllMenuKeys())
      // console.log(Toolbar.data)
    }

    /**
     * 提交按钮
     * @type {submit<function>}
     */
    const submitDisable = computed(() => {
      return (article.title && article.description);
    });
    const submit = () => {
      article.content = valueHtml.value;
      console.log(article)
      axios.post('/article/save', article).then((res) => {
        const data = res.data
        if (data.status === 10000) {
          message.success('文章保存成功');
          router.push('/');
          console.log(data);
        }
      })
    }


    //读取文章内容
    async function initArticle() {
      let router = useRouter();
      const articleId = router.currentRoute.value.query.articleId;
      if (articleId) {
        let res = await axios.get('/article/select?articleId=' + articleId);
        const result = res.data
        if (result.status === 10000) {
          console.log("result", result);
          article.id = articleId;
          article.title = result.content.title;
          article.description = result.content.description;
          article.cityName = result.content.cityName;
          valueHtml.value = result.content.content;
        }
      }
    }


    // 模拟 ajax 异步获取内容
    onMounted(() => {
      let router = useRouter();
      // console.log("route", router.currentRoute.value.query)
      // setTimeout(() => {
      //   valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
      // }, 100)
      initArticle();
      ifUser();
      getCity();
    })

    return {
      article,
      city,
      value,
      filterOption,
      handleCitySelect,
      handleBlur,
      handleFocus,
      handleChange,
      editorRef,
      valueHtml,
      mode: 'simple', // 或 'default'
      toolbarConfig,
      editorConfig,
      handleCreated,
      submitDisable,
      submit
    };
  }
}
</script>

<style scoped>

</style>